// 生成随机字符串
// User: 青锋真人<zengwanzhong@movee.cn>
// Datetime: 2020/2/10 14:27
package random

import (
	"math/rand"
	"sync"
	"time"
)

const charset = "abcdefghijklmnopqrstuvwxyz" +
	"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

var (
	seededRand *rand.Rand = rand.New(rand.NewSource(time.Now().UnixNano()))
	randStrMu  sync.Mutex
)

func RandomStringWithCharset(length int, charset string) string {
	b := make([]byte, length)
	for i := range b {
		b[i] = charset[intn(len(charset))]
	}
	return string(b)
}

func RandomString(length int) string {
	return RandomStringWithCharset(length, charset)
}

// 自己创建的随机种子，是非并发安全的
// 而默认的 globalRand 则是并发安全的
func intn(n int) int {
	randStrMu.Lock()
	defer func() {
		randStrMu.Unlock()
	}()
	return seededRand.Intn(n)
}
